﻿using System;
using System.Collections.Generic;
using RaytracerLib.MathLib;
using YAXLib;

namespace RaytracerLib.Layers
{
    public class TransparentOperationLayer : BinaryLayer
    {
        private Layer m_alpha;

        public TransparentOperationLayer(Layer a_childLayer1,
            Layer a_childLayer2, Layer a_alpha)
            : base(a_childLayer1, a_childLayer2)
        {
            Alpha = a_alpha;
        }

        public override ColorFloat GetColor(Vector2 a_uv, Intersection a_intersection)
        {
            double alpha = Alpha.GetValue(a_uv, a_intersection);
            return ChildLayer2.GetColor(a_uv, a_intersection) * alpha +
                ChildLayer1.GetColor(a_uv, a_intersection) * (1 - alpha);
        }

        public override double GetValue(Vector2 a_uv, Intersection a_intersection)
        {
            double alpha = Alpha.GetValue(a_uv, a_intersection);
            return ChildLayer2.GetValue(a_uv, a_intersection) * alpha +
                ChildLayer1.GetValue(a_uv, a_intersection) * (1 - alpha);
        }

        public override Tangents GetTangents(Vector2 a_uv, Vector2 a_tx, Vector2 a_ty,
            Intersection a_intersection)
        {
            throw new InvalidOperationException();
        }

        public override IEnumerable<Layer> Children
        {
            get
            {
                yield return ChildLayer1;
                yield return ChildLayer2;
                yield return Alpha;
            }
        }

        [YAXNode]
        public Layer Alpha
        {
            get
            {
                return m_alpha;
            }
            set
            {
                if (m_alpha != null)
                    m_alpha.Parent = null;
                m_alpha = value;
                if (m_alpha != null)
                    m_alpha.Parent = this;
            }
        }
    }
}